import flet as ft


class MainView(ft.Column):
    def __init__(self, page: ft.Page):
        super().__init__()
        self.page = page
        self.expand = True

        # 创建一个 ft.Ref 实例
        self.text_ref = ft.Ref[ft.Text]()

        # 构建 UI
        self.build_ui()

    def build_ui(self):
        # 使用 ft.Ref 绑定到 Text 控件
        text_control = ft.Text(
            "初始文本",
            ref=self.text_ref,  # 绑定 ft.Ref
            size=24,
            color=ft.colors.GREEN_800,
            weight=ft.FontWeight.BOLD
        )

        # 按钮，点击后更新 Text 控件的文本
        button = ft.FilledButton(
            "更新文本",
            on_click=self.update_text
        )

        self.controls = [
            text_control,
            button
        ]

    def update_text(self, e):
        # 通过 ft.Ref 访问并更新 Text 控件的文本
        if self.text_ref.current:
            self.text_ref.current.value = "更新后的文本"
            self.text_ref.current.update()


def main(page: ft.Page):
    page.title = "Flet Ref 示例"
    page.add(MainView(page))


ft.app(target=main)
